<template>
    <div style="height: 100%;">
        <div style="display: flex" v-if="dataSource.length > 1">
            <div v-for="(item, index) in dataSource"
                :class="`data-index cursor-pointer forbid-select font-auto-resize ${currentIndex === index ? 'select' : ''}`"
                :style="`width:${100 / dataSource.length}%`" @click="changeIndex(index)" @dblclick="refresh"
                :key="index">
                {{ item.Name }}
            </div>
        </div>
        <el-scrollbar ref="scrollRef"
            :style="`height:${dataSource.length > 1 ? 'calc(100% - var(--font-size) * 1.8 - 12px)' : '100%'}; width: 100%; `">
            <el-descriptions :column="1" border>
                <el-descriptions-item :label="map[key].name" :labelClassName="`label ${key}`"
                    v-for="key in Object.keys(currentDataSource)" :key="key">
                    <div v-if="key === 'PoolingCount'" style="color: #08c;cursor: pointer;width: fit-content"
                        class="forbid-select cursor-pointer" @click="showPool = true">
                        {{ currentDataSource[key] }} (点击查看)
                    </div>
                    <div v-else>{{ currentDataSource[key] }}</div>
                </el-descriptions-item>
            </el-descriptions>
        </el-scrollbar>

        <el-drawer v-model="showPool" direction="ltr" :show-close="false" @open="openPool" append-to-body
            :before-close="beforeClosePool" :close-on-press-escape="false" size="80%" @closed="closed">
            <template #header>
                <div class="font-auto-resize">
                    Pooling Connection Info List for Datasource-{{ name }}
                </div>
            </template>
            <el-table :data="poolInfo" border height="100%" header-cell-class-name="el-table-header-cell"
                cell-class-name="el-table-cell" class="e-page">
                <el-table-column fixed prop="connectionId" label="id" min-width="120" />
                <el-table-column prop="useCount" label="useCount" :width="fontAutoResize.size_6.value" />
                <el-table-column prop="keepAliveCheckCount" label="keepAliveCheckCount"
                    :min-width="fontAutoResize.size_12.value" />
                <el-table-column prop="lastActiveTime" label="lastActiveTime" :width="fontAutoResize.size_11.value" />
                <el-table-column prop="connectTime" label="connectTime" :width="fontAutoResize.size_11.value" />
                <el-table-column prop="holdability" label="holdability" :width="fontAutoResize.size_11.value" />
                <el-table-column prop="transactionIsolation" label="transactionIsolation"
                    :min-width="fontAutoResize.size_11.value" />
                <el-table-column prop="autoCommit" label="autoCommit" :width="fontAutoResize.size_8.value">
                    <template #default="scope">
                        {{ scope.row.autoCommit }}
                    </template>
                </el-table-column>
                <el-table-column prop="readoOnly" label="readoOnly" :width="fontAutoResize.size_8.value">
                    <template #default="scope">
                        {{ scope.row.readoOnly }}
                    </template>
                </el-table-column>
            </el-table>
        </el-drawer>


    </div>
</template>
<script setup>
import { useModalSize, useRequest } from "@usehook"
import { fontAutoResize } from "@/utils/setting"

const map = {
    "DbType": { "name": "*数据库类型", "description": "数据库类型" },
    "DriverClassName": { "name": "*驱动类名", "description": "JDBC驱动的类名" },
    "URL": { "name": "*连接地址", "description": "JDBC连接字符串" },
    "UserName": { "name": "*用户名", "description": "指定建立连接时使用的用户名" },
    "FilterClassNames": { "name": "*filter类名", "description": "filter的类名" },
    "WaitThreadCount": { "name": "等待线程数量", "description": "当前等待获取连接的线程数" },
    "NotEmptyWaitCount": { "name": "累计总次数", "description": "获取连接时累计等待多少次" },
    "NotEmptyWaitMillis": { "name": "等待总时长", "description": "获取连接时累计等待多长时间" },
    "PoolingCount": { "name": "池中连接数", "description": "当前连接池中的数目" },
    "PoolingPeak": { "name": "池中连接数峰值", "description": "连接池中数目的峰值" },
    "PoolingPeakTime": { "name": "池中连接数峰值时间", "description": "连接池数目峰值出现的时间" },
    "ActiveCount": { "name": "活跃连接数", "description": "当前连接池中活跃连接数" },
    "ActivePeak": { "name": "活跃连接数峰值", "description": "连接池中活跃连接数峰值" },
    "ActivePeakTime": { "name": "活跃连接数峰值时间", "description": "活跃连接池峰值出现的时间" },
    "InitialSize": { "name": "*初始化连接大小", "description": "连接池建立时创建的初始化连接数" },
    "MinIdle": { "name": "*最小空闲连接数", "description": "连接池中最小的活跃连接数" },
    "MaxActive": { "name": "*最大连接数", "description": "连接池中最大的活跃连接数" },
    "QueryTimeout": { "name": "*查询超时时间", "description": "查询超时时间" },
    "TransactionQueryTimeout": { "name": "*事务查询超时时间", "description": "事务查询超时时间" },
    "LoginTimeout": { "name": "*登录超时时间", "description": "" },
    "ValidConnectionCheckerClassName": { "name": "*连接有效性检查类名", "description": "" },
    "ExceptionSorterClassName": { "name": "*ExceptionSorter类名", "description": "" },
    "TestOnBorrow": { "name": "*获取连接时检测", "description": "是否在获得连接后检测其可用性" },
    "TestOnReturn": { "name": "*连接放回连接池时检测", "description": "是否在连接放回连接池后检测其可用性" },
    "TestWhileIdle": { "name": "*空闲时检测", "description": "是否在连接空闲一段时间后检测其可用性" },
    "DefaultAutoCommit": { "name": "*默认autocommit设置", "description": "" },
    "DefaultReadOnly": { "name": "*默认只读设置", "description": "" },
    "DefaultTransactionIsolation": { "name": "*默认事务隔离", "description": "" },
    "LogicConnectCount": { "name": "逻辑连接打开次数", "description": "产生的逻辑连接建立总数" },
    "LogicCloseCount": { "name": "逻辑连接关闭次数", "description": "产生的逻辑连接关闭总数" },
    "LogicConnectErrorCount": { "name": "逻辑连接错误次数", "description": "产生的逻辑连接出错总数" },
    "PhysicalConnectCount": { "name": "物理连接打开次数", "description": "产生的物理连接建立总数" },
    "PhysicalCloseCount": { "name": "物理关闭数量", "description": "产生的物理关闭总数" },
    "PhysicalConnectErrorCount": { "name": "物理连接错误次数", "description": "产生的物理连接失败总数" },
    "DiscardCount": { "name": "校验失败废弃连接数", "description": "校验连接失败丢弃连接次数" },
    "ExecuteCount": { "name": "执行数", "description": "" },
    "ExecuteUpdateCount": { "name": "ExecuteUpdateCount", "description": "" },
    "ExecuteQueryCount": { "name": "ExecuteQueryCount", "description": "" },
    "ExecuteBatchCount": { "name": "ExecuteBatchCount", "description": "" },
    "ErrorCount": { "name": "错误数", "description": "" },
    "CommitCount": { "name": "提交数", "description": "事务提交次数" },
    "RollbackCount": { "name": "回滚数", "description": "事务回滚次数" },
    "PSCacheAccessCount": { "name": "PSCache访问次数", "description": "PSCache访问总数" },
    "PSCacheHitCount": { "name": "PSCache命中次数", "description": "PSCache命中次数" },
    "PSCacheMissCount": { "name": "PSCache不命中次数", "description": "PSCache不命中次数" },
    "StartTransactionCount": { "name": "事务启动数", "description": "事务开始的个数" },
    "TransactionHistogram": {
        "name": "事务时间分布",
        "description": "事务运行时间分布，分布区间为[0-1 ms, 1-10 ms, 10-100 ms, 100-1 s, 1-10 s, 10-100 s, >100 s]"
    },
    "ConnectionHoldTimeHistogram": {
        "name": "连接持有时间分布",
        "description": "连接持有时间分布，分布区间为[0-1 ms, 1-10 ms, 10-100 ms, 100ms-1s, 1-10 s, 10-100 s, 100-1000 s, >1000 s]"
    },
    "RemoveAbandoned": { "name": "RemoveAbandoned", "description": "" },
    "ClobOpenCount": { "name": "Clob打开次数", "description": "Clob打开数" },
    "BlobOpenCount": { "name": "Blob打开次数", "description": "Blob打开数" },
    "KeepAliveCheckCount": { "name": "KeepAlive检测次数", "description": "KeepAlive检测次数" },
    "KeepAlive": { "name": "*KeepAlive", "description": "" },
    "FailFast": { "name": "*FailFast", "description": "" },
    "MaxWait": { "name": "*MaxWait", "description": "" },
    "MaxWaitThreadCount": { "name": "*MaxWaitThreadCount", "description": "" },
    "PoolPreparedStatements": { "name": "*PoolPreparedStatements", "description": "" },
    "MaxPoolPreparedStatementPerConnectionSize": {
        "name": "*MaxPoolPreparedStatementPerConnectionSize",
        "description": ""
    },
    "MinEvictableIdleTimeMillis": { "name": "*MinEvictableIdleTimeMillis", "description": "" },
    "MaxEvictableIdleTimeMillis": { "name": "*MaxEvictableIdleTimeMillis", "description": "" },
    "LogDifferentThread": { "name": "*LogDifferentThread", "description": "" },
    "RecycleErrorCount": { "name": "逻辑连接回收重用次数", "description": "逻辑连接回收重用次数" },
    "PreparedStatementOpenCount": { "name": "真实PreparedStatement打开次数", "description": "真实PreparedStatement打开次数" },
    "PreparedStatementClosedCount": { "name": "真实PreparedStatement关闭次数", "description": "真实PreparedStatement关闭次数" },
    "UseUnfairLock": { "name": "*UseUnfairLock", "description": "" },
    "InitGlobalVariants": { "name": "*InitGlobalVariants", "description": "" },
    "InitVariants": { "name": "*InitVariants", "description": "" },
    "PoolConnectionInfo": { "name": "PoolConnectionInfo", "description": "Info for polling connection." },
    "SqlList": { "name": "SqlList", "description": "Info for SQL." }
}

let dataSource = $ref([])
let currentIndex = $ref(0)
let showPool = $ref(false)
let poolInfo = $ref([])
let poolInterval = $ref(null)
let currentDataSource = $ref({})
let identity = $ref("")
let name = $ref("")
let query = $ref(false)

const scrollRef = $ref(null)

const beforeClosePool = (done) => {
    useModalSize(false)
    if (poolInterval) {
        clearInterval(poolInterval)
        poolInterval = null
    }
    done()
}
const closed = () => {
    poolInfo = []
}
const openPool = () => {
    useModalSize()
    getPoolInfo()
    poolInterval = setInterval(() => {
        getPoolInfo()
    }, 10000)
}
const getPoolInfo = () => {
    useRequest({ url: "/dataSource/druid/connectionInfo-" + identity + ".json" }).then(resp => {
        if (resp && resp.ResultCode === 1) {
            poolInfo = resp.Content
        }
    })
}
const getCurrentDataSourceInfo = () => {
    const _dataSource = dataSource.length > 0 ? dataSource[currentIndex] : {}
    const { Name, Identity, ...ds } = _dataSource
    currentDataSource = ds
    name = Name
    identity = Identity
}
const changeIndex = (index) => {
    nextTick(() => {
        scrollRef.wrapRef.scrollTop = 0
    })
    currentIndex = index
    getCurrentDataSourceInfo()
}
const refresh = () => {
    if (query) return
    query = true
    useRequest({ url: "/dataSource/druid/datasource.json" }).then(resp => {
        if (resp && resp.ResultCode === 1) {
            dataSource = resp.Content
            getCurrentDataSourceInfo()
        }
    }).finally(() => {
        setTimeout(() => {
            query = false
        }, 5000)
    })
}

onMounted(() => {
    useRequest({ url: "/dataSource/druid/datasource.json" }).then(resp => {
        if (resp && resp.ResultCode === 1) {
            dataSource = resp.Content
            getCurrentDataSourceInfo()
        }

        nextTick(() => {
            for (let ele of document.getElementsByClassName("el-descriptions-row")) {
                const td = document.createElement("td")
                td.classList.add("el-descriptions-item__cell")
                td.classList.add("el-descriptions-item__content")
                td.classList.add("description")
                const name = ele.querySelector("th").classList[ele.querySelector("th").classList.length - 1]
                td.innerText = map[name].description
                ele.append(td)
            }
        })
    })
})
</script>

<style scoped>
:deep(.label) {
    width: 250px;
}

:deep(.el-descriptions-row th) {
    text-align: right !important;
}

:deep(.data-index) {
    text-align: center;
    border: 1px solid #99a9bf;
    margin: 5px 0;
    border-radius: 5px;
    transition: background .2s ease-out;
    font-size: 14px;
}

:deep(.data-index + .data-index) {
    margin-left: 5px;
}

:deep(.select) {
    background: rgb(114 114 114 / 40%);
    transition: background .5s ease-out;
}

:deep(.description) {
    background: #fafafa;
    width: 20%;
}

:deep(.el-drawer__body) {
    padding: 0 5px;
}
</style>